<template>
  <div>
    <basic-container>
      <el-tabs v-model="tabItem" @tab-click="handleClick">
        <el-tab-pane label="待维保" name="0" >
          <avue-crud :option="option"
                     :data="gridData"
                     :table-loading="loading"
                     :page="page"
                     @current-change="currentPageChange"
                     @size-change="sizeChange"
                     ref="crud">
            <template slot-scope="scope" slot="approvalNumber" v-if="scope.row.application">{{ scope.row.application.approvalNumber }}</template>
            <template slot-scope="scope" slot="coded" v-if="scope.row.equipment">{{ scope.row.equipment.coded }}</template>
            <template slot-scope="scope" slot="name" v-if="scope.row.equipment">{{ scope.row.equipment.name }}</template>
            <template slot-scope="scope" slot="marking" v-if="scope.row.equipment">{{ scope.row.equipment.marking }}</template>
            <template slot-scope="scope" slot="brand" v-if="scope.row.equipment">{{ scope.row.equipment.brand }}</template>
            <template slot-scope="scope" slot="locationName" v-if="scope.row.equipment">{{ scope.row.application.locationName }}</template>
            <template slot-scope="scope" slot="menu">
              <el-button type="primary" size="small"  plain @click="addFormData(scope.row, scope.index)">添加维保单</el-button>
              <el-button type="primary" size="small"  plain @click.stop="applyFormSubmit(scope.row,scope.index)">申请单</el-button>
            </template>
          </avue-crud>
        </el-tab-pane>

        <el-tab-pane label="已维保" name="1">
          <!-- <el-form :inline="true" :model="searchForm" class="demo-form-inline" size="mini">
            <el-form-item label="维保类型:">
              <el-select v-model="searchForm.type">
                <el-option v-for="(item, index) in maintenanceTypeOptionList"
                           :key="index"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="设备类别:" v-model="searchForm.category">
              <el-cascader v-model="searchForm.category"
                           :options="equipmentTypeList"
                           :props="{ expandTrigger: 'hover' }"
                           @change="equipmentTypeChange">
              </el-cascader>
            </el-form-item>

            <el-form-item label="设备编码:">
              <el-input v-model="searchForm.code" placeholder="请输入设备编码"></el-input>
            </el-form-item>
            <el-form-item label="设备名称:">
              <el-input v-model="searchForm.name" placeholder="请输入设备名称"></el-input>
            </el-form-item>
            <el-form-item label="设备型号:">
              <el-input v-model="searchForm.number" placeholder="请输入设备型号"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchFormSubmit">搜索</el-button>
              <el-button @click="searchForm = {}">重置</el-button>
            </el-form-item>
          </el-form> -->

          <avue-crud :option="scrapOption"
                     :data="gridData"
                     :table-loading="scrapLoading"
                     :page="page"
                     @current-change="currentPageChange"
                     @size-change="sizeChange"
                     ref="crud">
            <template slot-scope="scope" slot="approvalNumber" v-if="scope.row.application">{{ scope.row.application.approvalNumber }}</template>
            <template slot-scope="scope" slot="coded" v-if="scope.row.equipment">{{ scope.row.equipment.coded }}</template>
            <template slot-scope="scope" slot="marking" v-if="scope.row.equipment">{{ scope.row.equipment.marking }}</template>
            <template slot-scope="scope" slot="brand" v-if="scope.row.equipment">{{ scope.row.equipment.brand }}</template>
            <template slot-scope="scope" slot="locationName" v-if="scope.row.equipment">{{ scope.row.application.locationName }}</template>
            <template slot-scope="scope" slot="maintenanceResults">{{ scope.row.maintenanceResults === 0 ? '合格' : '不合格' }}</template>
            <template slot-scope="scope" slot="unit">{{ scope.row.unit !== null ? scope.row.unit : '无' }}</template>
            <template slot-scope="scope" slot="maintenanceCharge">{{ scope.row.maintenanceCharge !== null ? scope.row.maintenanceCharge : 0 }}</template>
            <template slot-scope="scope" slot="personAndUpdateTime">{{ scope.row.person !== null ? scope.row.person : '无' }} / {{ scope.row.updateTime }}</template>
            <template slot-scope="scope" slot="lastUpdateName" v-if="scope.row.equipment">
              {{ scope.row.equipment.lastOpenName !== null ? scope.row.equipment.lastOpenName : '无' }} / {{ scope.row.equipment.alterTime }}
            </template>
            <template slot-scope="scope" slot="menu">
              <el-button type="primary" size="small"  plain @click="seeFormScrap(scope.row, scope.index)">查看</el-button>
              <el-button type="primary" size="small"  plain @click.stop="updateSubmit(scope.row,scope.index)">修改</el-button>
              <el-button type="primary" size="small"  plain @click.stop="applyFormSubmit(scope.row,scope.index)">申请单</el-button>
            </template>
          </avue-crud>
        </el-tab-pane>
      </el-tabs>
    </basic-container>

    <!-- 添加或修改维保单 -->
    <el-dialog :title="addModeFormTitle" :visible.sync="addMode" width="60%" center>
      <div class="lineDiv"></div>
      <el-form :model="formData" ref="formData" class="demo-form-inline" size="mini"  label-width="120px">
        <el-row :span="24">
          <el-col :span="12" style="text-align: left;">
            <el-form-item label="设备类别：">{{ formData.equipmentType }}</el-form-item>
            <el-form-item label="设备名称：">{{ formData.name }}</el-form-item>
            <el-form-item label="品牌：">{{ formData.brand }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编码：">{{ formData.coded }}</el-form-item>
            <el-form-item label="型号：">{{ formData.marking }}</el-form-item>
            <el-form-item label="存放位置：">{{ formData.locationName }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 添加 -->
      <div class="lineDiv"></div>
      <el-form :model="addFormInfo" v-show="addFormDialog = 1" label-width="120px" size="mini">
        <el-row :span="24">
          <el-col :span="12">
            <el-form-item label="维保类型：">
              {{ formData.type }}
<!--              <el-select v-model="addFormInfo.type">-->
<!--                <el-option v-for="(item, index) in maintenanceTypeOptionList"-->
<!--                           :key="index"-->
<!--                           :label="item.label"-->
<!--                           :value="item.value">-->
<!--                </el-option>-->
<!--              </el-select>-->
            </el-form-item>
            <el-form-item label="维保单位：">
              <el-input type="text" v-model="addFormInfo.unit"></el-input>
            </el-form-item>
            <el-form-item label="维保人：">
              <el-input type="text" v-model="addFormInfo.person"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item><span>&nbsp;</span></el-form-item>
            <el-form-item label="维保费用(元)：">
              <el-input type="text" v-model="addFormInfo.money"></el-input>
            </el-form-item>
            <el-form-item label="联系方式：">
              <el-input type="text" v-model="addFormInfo.personPhone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :span="24">
        <el-form-item label="维保时间：">
          <el-date-picker
              v-model="addFormInfo.maintenanceTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="维保结果：">
          <el-radio-group v-model="addFormInfo.result">
            <el-radio :label="0">合格</el-radio>
            <el-radio :label="1">不合格</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="维保情况：" style="display: inline-table; width: 100%;" >
          <el-input type="textarea" v-model="addFormInfo.content" style="width: 58%;"></el-input>
        </el-form-item>
        <div class="lineDiv"></div>
        <div style="text-align: center;">
          <el-button size="medium" @click="addMode = false">关闭</el-button>
          <el-button size="medium" type="primary" @click="confirmFormSubmit('formData')">确定</el-button>
        </div>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- 查看维保单 -->
    <el-dialog title="维保单" :visible.sync="seeMode" width="60%" center>
      <div class="lineDiv"></div>
      <el-form :model="formData" ref="formData" class="demo-form-inline" size="mini"  label-width="120px">
        <el-row :span="24">
          <el-col :span="12" style="text-align: left;">
            <el-form-item label="设备类别：" v-if="this.formData.equipmentType">{{ formData.equipmentType }}</el-form-item>
            <el-form-item label="设备名称：">{{ formData.name }}</el-form-item>
            <el-form-item label="品牌：">{{ formData.brand }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编码：">{{ formData.coded }}</el-form-item>
            <el-form-item label="型号：">{{ formData.marking }}</el-form-item>
            <el-form-item label="存放位置：">{{ formData.locationName }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 添加 -->
      <div class="lineDiv"></div>
      <el-form :model="addFormInfo"  ref="formData" class="demo-form-inline" size="mini"  label-width="120px">
        <el-row :span="24">
          <el-col :span="12" style="text-align: left;">
            <el-form-item label="维保类型：">{{ formData.maintenanceType }}</el-form-item>
            <el-form-item label="维保单位：">{{ formData.unit }}</el-form-item>
            <el-form-item label="维保人：">{{ formData.person }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item><span>&nbsp;</span></el-form-item>
            <el-form-item label="维保费用(元)：">{{ formData.maintenanceCharge }}</el-form-item>
            <el-form-item label="联系方式：">{{ formData.personPhone }}</el-form-item>
          </el-col>
        </el-row>
        <el-row :span="24">
          <el-form-item label="维保时间：">{{ formData.startTime }}<span>至</span>{{ formData.endTime }}</el-form-item>
          <el-form-item label="维保结果：">{{ formData.maintenanceResults }}</el-form-item>
          <el-form-item label="维保情况：">{{ formData.situation }}</el-form-item>
        </el-row>
        <div class="lineDiv"></div>
        <div style="text-align: center;">
          <!--<el-button size="medium" type="primary" @click="printFormInfo">打印</el-button>-->
          <el-button size="medium" @click="seeMode = false">关闭</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
import  { getEquipmentType } from '@/api/equipment/device/management.js'
import { DepartmentTreeVChildrenNull, getDepartmentTreeOfId } from '@/util/util'
import { option , scrapOption } from "@/const-personal/equipment/aintenance/maintenance-execution.js"
import { getExecutionList, getMaintenanceById, addExecutionList } from '@/api/equipment/aintenance/maintenance-execution.js'

export default {
  data () {
    return {
      option: option,
      scrapOption:scrapOption,
      loading: false,
      scrapLoading:false,
      addMode: false,
      seeMode: false,
      addForm: {},
      searchForm: {
        type: [],
        category: [],
        // location: '',
        code: '',
        name: '',
        number: ''
      },
      page: {
          total: 0, //总页数
          currentPage: 1, //当前页数
          pageSize: 10 , //每页显示多少条
          pageSizes: [ 5, 10 ] //显示多少条数据
      },
      gridData: [{
          name:'测试',
          idno:'测试'
      }],
      isAddForm: '', //添加或修改报废单
      formData: {
        id: '',
        equipmentType: '',
        coded: '',
        name: '',
        marking: '',
        brand: '',
        location: '',
        maintenanceType: '',
        unit: '',
        startTime: '',
        endTime: ''
      }, //dialog数据
      maintenanceTypeOptionList: [
        { value: '0', label: '保养' },
        { value: '1', label: '校准' },
        { value: '2', label: '维修' }
      ],  //维保类型
      equipmentTypeList: [],  //设备类别列表
      selectedEquipmentType: [],
      updateFormInfo: {
        date: [],
        result: ''
      },
      tabItem: '0',
      addFormDialog: 0,
      deviceInfo: {}, // 设备信息
      addFormInfo: {
        type: '',
        maintenanceTime: [],
        result: '',
        content: '',
        money: 0,
        personPhone: '',
        person: '',
        unit: ''
      }, //添加报废单
      addModeFormTitle: ''
    }
  },
  components: {},
  created () {
    if (this.$route.query.tabItem) {
      this.tabItem = this.$route.query.tabItem
    }
  },
  watch: {
    $route (to, from) {
      if (this.$route.query.tabItem) {
        this.tabItem = this.$route.query.tabItem
        this._getAllList()
      }
    }
  },
  methods: {
    // 打印
    printFormInfo () {
      console.log('打印')
    },
    // 添加报废单
    addFormData (row, index) {
      this.addMode = true
      this.addModeFormTitle = '添加维保单'
      this.addFormDialog = 1
      this.addFormInfo = {}
      this.formData = {
        equipmentTypeId: getDepartmentTreeOfId(this.equipmentTypeList, row.equipment.equipmentTypeId).label,
        id: row.id,
        coded: row.equipment.coded,
        name: row.equipment.name,
        marking: row.equipment.marking,
        brand: row.equipment.brand,
        location: row.equipment.location,
        type: this.maintenanceTypeOptionList.filter(i => i.value === row.application.maintenanceType.toString())[0].label,
        locationName: row.application.locationName,
        equipmentType: getDepartmentTreeOfId(this.equipmentTypeList, row.equipment.equipmentTypeId).label
      }

    },
    // 格式化数据
    formatFormInfo (row) {
      console.log('格式化')
      console.log(row)
      this.formData = {
        id: row.id,
        coded: row.equipment.coded,
        name: row.equipment.name,
        marking: row.equipment.marking,
        brand: row.equipment.brand,
        location: row.equipment.location,
        type: row.equipment.equipmentTypeId,
        equipmentType: row.equipment.equipmentType,
        maintenanceType: this.maintenanceTypeOptionList.filter(item => item.value === (row.application.maintenanceType).toString())[0].label,
        unit: row.unit,
        person: row.person,
        money: row.maintenanceCharge,
        tel: row.historyMoney,
        equipmentId: row.equipment.id,
        applicationTime: row.application.applicationTime,
        approvalNumber: row.application.approvalNumber,
        approvalStatus: row.application.approvalStatus,
        locationName: row.application.locationName,
        remakes: row.application.remakes,
        applicationId: row.application.id,
        maintenanceTime: [],
      }
      console.log(this.formData)
    },
    // 查看
    seeFormScrap (row) {
      this.seeMode = true
      console.log(row)
      console.log(this.equipmentTypeList)
      this.formData = {
        id: row.id,
        equipmentType: getDepartmentTreeOfId(this.equipmentTypeList, row.equipment.equipmentTypeId).label,
        name: row.equipment.name,
        coded: row.equipment.coded,
        marking: row.equipment.marking,
        brand: row.equipment.brand,
        location: row.equipment.location,
        maintenanceType: this.maintenanceTypeOptionList.filter(item => item.value === (row.application.maintenanceType).toString())[0].label,
        unit: row.unit,
        maintenanceCharge: row.maintenanceCharge,
        person: row.person,
        personPhone: row.personPhone,
        startTime: row.startTime,
        endTime: row.endTime,
        maintenanceResults: row.maintenanceResults === 0 ? '未维保' : '已维保',
        situation: row.situation,
        historyMoney: row.historyMoney,
        equipmentId: row.equipment.id,
        applicationTime: row.application.applicationTime,
        approvalNumber: row.application.approvalNumber,
        approvalStatus: row.application.approvalStatus,
        locationName: row.application.locationName,
        remakes: row.application.remakes,
        applicationId: row.application.id,
      }
    },
    // 修改
    updateSubmit (row) {
      this.addMode = true
      this.addModeFormTitle = '修改维保单'
      this.addFormDialog = 2
      console.log(getDepartmentTreeOfId(this.equipmentTypeList, row.equipment.equipmentTypeId).label)
      this.formData = {
        id: row.id,
        equipmentType: getDepartmentTreeOfId(this.equipmentTypeList, row.equipment.equipmentTypeId).label,
        name: row.equipment.name,
        coded: row.equipment.coded,
        marking: row.equipment.marking,
        brand: row.equipment.brand,
        location: row.equipment.location,
        equipmentId: row.equipment.id,
        applicationTime: row.application.applicationTime,
        approvalNumber: row.application.approvalNumber,
      }
      this.addFormInfo = {
        type: this.maintenanceTypeOptionList.filter(item => item.value === (row.application.maintenanceType).toString())[0].label,
        unit: row.unit,
        money: row.maintenanceCharge,
        person: row.person,
        personPhone: row.personPhone,
        maintenanceTime: [row.startTime, row.endTime],
        result: row.maintenanceResults,
        content: row.situation,
      }
    },
    // 添加或修改提交数据
    confirmFormSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if(valid) {
          console.log(this.addFormInfo)
          const params = {
            application: {
              applicationTime: this.formData.applicationTime,
              approvalNumber: this.formData.approvalNumber,
              approvalStatus: Number(this.formData.approvalStatus),
              equipmentId: this.formData.equipmentId,
              id: this.formData.applicationId,
              locationName: this.formData.locationName,
              maintenanceType: Number(this.addFormInfo.type),
              remakes: this.formData.content,
            },
            endTime: moment(this.addFormInfo.maintenanceTime[1]).format('YYYY-MM-DD'),
            isResults: Number(this.addFormInfo.result),
            equipmentId: this.formData.equipmentId,
            id: this.formData.id,
            maintenanceCharge: Number(this.addFormInfo.money),
            // maintenanceInstructions: this.addFormInfo.content,
            startTime: moment(this.addFormInfo.maintenanceTime[0]).format('YYYY-MM-DD'),
            maintenanceResults: 0,
            person: this.addFormInfo.person,
            personPhone: this.addFormInfo.personPhone,
            situation: this.addFormInfo.content,
            unit: this.addFormInfo.unit,
          }
          console.log(params)
          if (this.addModeFormTitle === '添加维保单' && this.tabItem === '0') {
            console.log('添加')
            this.addExecutionForm(params)
          }
          if (this.addModeFormTitle === '修改维保单'  && this.tabItem === '1') {
            console.log('修改')
            this.addExecutionForm(params)
          }
        }
      })
    },
    addExecutionForm (data) {
      addExecutionList(data).then(res => {
        if (res.data.code === 200) {
          console.log(res)
          this.addMode = false
          this._getAllList()
          this.$notify({ title: '操作成功', type: 'success', message: '操作成功' })
        } else {
          this.$notify.error({ title: '操作失败', type: 'dengar', message: res.data.message })
        }
      })
    },
    // 待维保申请单
    applyFormSubmit (row) {
      this.seeMode = true
      getMaintenanceById({ id: row.id }).then(res => {
        if (res.data.code === 200) {
          const result = res.data.data
          this.formData = {
            equipmentType: getDepartmentTreeOfId(this.equipmentTypeList, result.application.equipment.equipmentTypeId).label,
            name: result.application.equipment.name,
            brand: result.application.equipment.brand,
            coded: result.application.equipment.coded,
            marking: result.application.equipment.marking,
            locationName: result.application.locationName,
            maintenanceType: this.maintenanceTypeOptionList.filter(item => item.value === (row.application.maintenanceType).toString())[0].label,
            unit: result.unit,
            person: result.person,
            maintenanceCharge: result.maintenanceCharge,
            personPhone: result.personPhone,
            startTime: result.startTime,
            endTime: result.endTime,
            maintenanceResults: result.maintenanceResults === 0 ? '未维保' : '已维保',
            situation: result.situation
          }
        }
      })
    },
    // 根据条件查询已报废
    searchFormSubmit () {
      // type  category  location  code  name  number
      const params = {
        page: this.page.currentPage,
        size: this.page.pageSize,
        maintenance: {
          maintenanceResults: 1,

        }
      }
      this._getAllList(params)
    },
    equipmentTypeChange (value) {
      console.log(value)
      this.selectedEquipmentType = value
    },
    // tag改变获取数据
    handleClick (value) {
      this.tabItem = value.name
      this.$router.push({ path: '/aintenance/maintenanceExecution', query: { tabItem: this.tabItem } });
      // this._getAllList()
    },
    sizeChange(val) {
      this.page.pageSize = val
      this._getAllList()
    },
    currentPageChange (val) {
      this.page.currentPage = val
      this._getList({
        page: this.page.currentPage,
        size: this.page.pageSize,
        maintenance: {
          maintenanceResults: this.tabItem === '0' ? 0 : 1
        }
      })
    },
    // 获取已报废列表或待废
    _getList (params) {
      getExecutionList(params).then(res => {
        if(res.data.code === 200) {
          this.gridData = res.data.data.list

          this.gridData.forEach(item => {
            item.maintenanceType = this.maintenanceTypeOptionList.filter(i => i.value === item.application.maintenanceType.toString())[0].label
          })

          this.gridData.forEach(item => {
            item.equipmentTypeName = getDepartmentTreeOfId(this.equipmentTypeList, item.equipment.equipmentTypeId).label
          })

          this.page.total = res.data.data.total
          this.page.currentPage = res.data.data.pageNum
          this.page.pageSize = res.data.data.pageSize
        } else {
          this.$notify.error(res.data.message)
        }
      })
    },
    // 获取设备类别和维保列表
    _getDeviceList(params) {
      getEquipmentType().then(res => {
        if (res.data.code === 200) {
          this.equipmentTypeList = DepartmentTreeVChildrenNull(res.data.data, [{ label:'全部', value:'-1' }])
          // 获取已报废列表或待废
          this._getList(params)
        }
      })
    },
    // 获取数据列表
    _getAllList () {
      let tabName = 0
      const params = {
        page: this.page.currentPage,
        size: this.page.pageSize
      }
      // 待废
      if (this.tabItem === '0') {
        tabName = 0
        const data = { ...params, maintenance: { maintenanceResults: tabName } }
        this._getDeviceList(data)
      }

      // 已废
      if (this.tabItem === '1') {
        tabName = 1
        const data = { ...params, maintenance: { maintenanceResults: tabName } }
        this._getDeviceList(data)
      }
    },
  },
  mounted () {
    this._getAllList()
  }
}
</script>

<style lang="scss">
.avue-crud__menu{
  min-height: 0px;
}
.el-divider{
  display: block;
  height: 1px;
  width: 100%;
  margin: 0 0 24px 0;
  background-color: #dcdfe6;
  position: relative;
}
.zindex1>.el-form-item__content{
   z-index: -1;
 }
.lineDiv {
  border-top: 1px solid #d6d6d6;
  margin: 20px 0;
  width: 100%;
}
</style>
